﻿package com.rbac.system.service.impl;

import com.rbac.system.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import jakarta.mail.internet.MimeMessage;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * 邮件服务实现类
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    
    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String fromEmail;
    
    private static final String EMAIL_PATTERN = 
        "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    
    private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    
    @Override
    public boolean sendVerificationCode(String to, String code, String type) {
        try {
            String subject = getSubjectByType(type);
            String htmlContent = buildVerificationCodeHtml(code, type);
            
            return sendHtmlEmail(to, subject, htmlContent);
        } catch (Exception e) {
            log.error("发送验证码邮件失败: to={}, type={}, error={}", to, type, e.getMessage());
            return false;
        }
    }
    
    @Override
    public boolean sendSimpleEmail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            log.info("简单邮件发送成功: to={}, subject={}", to, subject);
            return true;
        } catch (Exception e) {
            log.error("发送简单邮件失败: to={}, subject={}, error={}", to, subject, e.getMessage());
            return false;
        }
    }
    
    @Override
    public boolean sendHtmlEmail(String to, String subject, String htmlContent) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            
            mailSender.send(message);
            log.info("HTML邮件发送成功: to={}, subject={}", to, subject);
            return true;
        } catch (Exception e) {
            log.error("发送HTML邮件失败: to={}, subject={}, error={}", to, subject, e.getMessage());
            return false;
        }
    }
    
    @Override
    public String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
    
    @Override
    public boolean isValidEmail(String email) {
        return email != null && pattern.matcher(email).matches();
    }
    
    /**
     * 根据类型获取邮件主题
     */
    private String getSubjectByType(String type) {
        switch (type) {
            case "register":
                return "【RBAC权限管理系统】注册验证码";
            case "login":
                return "【RBAC权限管理系统】登录验证码";
            default:
                return "【RBAC权限管理系统】验证码";
        }
    }
    
    /**
     * 构建验证码邮件HTML内容
     */
    private String buildVerificationCodeHtml(String code, String type) {
        String action = "register".equals(type) ? "注册" : "登录";
        
        return "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta charset='UTF-8'>" +
                "<title>验证码</title>" +
                "</head>" +
                "<body style='font-family: Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 20px;'>" +
                "<div style='max-width: 600px; margin: 0 auto; background-color: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'>" +
                "<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;'>" +
                "<h1 style='margin: 0; font-size: 24px;'>RBAC权限管理系统</h1>" +
                "<p style='margin: 10px 0 0 0; opacity: 0.9;'>企业级后台管理平台</p>" +
                "</div>" +
                "<div style='padding: 40px 30px;'>" +
                "<h2 style='color: #333; margin-bottom: 20px;'>您的" + action + "验证码</h2>" +
                "<p style='color: #666; line-height: 1.6; margin-bottom: 30px;'>您正在进行" + action + "操作，请使用以下验证码完成验证：</p>" +
                "<div style='background-color: #f8f9fa; border: 2px dashed #667eea; border-radius: 8px; padding: 20px; text-align: center; margin: 30px 0;'>" +
                "<span style='font-size: 32px; font-weight: bold; color: #667eea; letter-spacing: 5px;'>" + code + "</span>" +
                "</div>" +
                "<p style='color: #999; font-size: 14px; line-height: 1.6;'>" +
                "• 验证码有效期为5分钟<br>" +
                "• 请勿将验证码告知他人<br>" +
                "• 如非本人操作，请忽略此邮件" +
                "</p>" +
                "</div>" +
                "<div style='background-color: #f8f9fa; padding: 20px; text-align: center; border-radius: 0 0 10px 10px; border-top: 1px solid #eee;'>" +
                "<p style='margin: 0; color: #999; font-size: 12px;'>此邮件由系统自动发送，请勿回复</p>" +
                "</div>" +
                "</div>" +
                "</body>" +
                "</html>";
    }
}


